package budo;

import java.util.Iterator;
import java.util.List;
import java.util.ServiceLoader;

import org.budo.launcher.service.BudoLauncherService;
import org.budo.support.lang.util.ListUtil;
import org.budo.support.lang.util.StringUtil;
import org.budo.support.slf4j.Slf4j;
import org.slf4j.Logger;

/**
 * @author lmw
 */
public class Launcher {
    private static final Logger log = Slf4j.getLogger();

    public static void main(String[] args) {
        Launcher launcher = new Launcher();
        launcher.run(args);
    }

    public void run(String[] args) {
        BudoLauncherService launcherService = this.loadLauncherService();

        log.info("#28 launcherService=" + launcherService + ", args=" + StringUtil.join(args) + ", this=" + this);
        launcherService.run(args);
    }

    private BudoLauncherService loadLauncherService() {
        ServiceLoader<BudoLauncherService> serviceLoader = ServiceLoader.load(BudoLauncherService.class);
        Iterator<BudoLauncherService> iterator = serviceLoader.iterator();

        List<BudoLauncherService> launcherServices = ListUtil.iteratorToList(iterator);
        if (null == launcherServices || launcherServices.isEmpty() || launcherServices.size() > 1) {
            throw new IllegalStateException("#37 no launcherService or multi launcherServices = " + launcherServices);
        }

        return launcherServices.get(0);
    }
}